#!/bin/env python

import cv2

windowName = "fact_detector"

new_operate1 = 11
new_operate2 = 3

def trackbarCallback(value):
    pass

def detector_face(gray_img):
    # 使用级联分类器(级联检测器) 加载人脸特征
    fact_detector_data = cv2.CascadeClassifier("../../resource/data/haarcascade_frontalface_alt.xml")
    # 检测人脸，输出坐标，x,y,w,h
    face_pos = fact_detector_data.detectMultiScale(gray_img, scaleFactor = new_operate1 / 10, minNeighbors = new_operate2)

    return face_pos


if __name__ == '__main__':
    cap = cv2.VideoCapture(0)
    if cap.isOpened():
        cv2.namedWindow(windowName, cv2.WINDOW_NORMAL)
        # cv2.resizeWindow(windowName, int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))

        cv2.createTrackbar('scaleFactor', windowName, new_operate1, 100, trackbarCallback)
        cv2.createTrackbar('minNeighbors', windowName, new_operate2, 30, trackbarCallback)
        cv2.setTrackbarMin('scaleFactor', windowName, 11)
        cv2.setTrackbarMin('minNeighbors', windowName, 1)

        while True:
            ret, frame = cap.read()
            if not ret: break
            gray_img = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

            new_operate1 = cv2.getTrackbarPos('scaleFactor', windowName)
            new_operate2 = cv2.getTrackbarPos('minNeighbors', windowName)
    
            face_pos = detector_face(gray_img)
            out_img = frame.copy()
            if len(face_pos) != 0:
                for x,y,w,h in face_pos:
                    cv2.rectangle(out_img, (x, y), (x + w, y + h), (0, 255, 0), thickness=2)
                face_num = face_pos.shape[0]
            else:
                face_num = 0
            cv2.putText(out_img, str(face_num), (10, 30), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 255))
            cv2.imshow(windowName, out_img)

            if cv2.waitKey(10) == ord('q'):
                break
    else:
        print("Error: VideoCapture failed")
    print('销毁窗口')
    cv2.destroyAllWindows()



